package com.system.core.sms.dto.mail;

import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import jakarta.mail.Authenticator;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import lombok.AllArgsConstructor;

@Configuration
@AllArgsConstructor
public class MailConfigBean {

	private final MailConfigProperty mailConfig;
	
	@Bean
	Session mailSession(){
		Properties properties = new Properties();
		properties.setProperty("mail.smtp.ssl.protocols", "TLSv1.2");
		properties.setProperty("mail.smtp.ssl.ciphers", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256");
		properties.setProperty("mail.smtp.host", getString(mailConfig.getHost())); // QQ 邮箱的 SMTP 服务器地址
		properties.setProperty("mail.smtp.port", getString(mailConfig.getPort())); // QQ 邮箱的 SMTP 服务器端口
		properties.setProperty("mail.smtp.auth", getString(mailConfig.getAuth())); // 需要进行身份验证
		properties.setProperty("mail.smtp.starttls.enable", getString(mailConfig.getTls())); // 启用TLS加密

		// 创建邮件会话对象
		Session session = Session.getInstance(properties, new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(getString(mailConfig.getUserName()), getString(mailConfig.getPasswd())); // 发件人的用户名和密码
			}
		});
		return session;
	}
	
	private String getString(String str) {
		if(str == null) {
			return StringUtils.EMPTY;
		} else {
			return str;
		}
	}
}
